// cloudfunctions/login/index.js
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-3gew2xhnadfbd1bd'
})

const db = cloud.database()
const _ = db.command

/**
 * 用户登录/注册云函数
 * 功能：
 * 1. 获取用户 openId
 * 2. 检查用户是否已注册
 * 3. 新用户自动注册
 * 4. 返回用户信息
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openId = wxContext.OPENID
  
  try {
    // 查询用户是否已存在
    const userQuery = await db.collection('users').where({
      _openid: openId
    }).get()
    
    let userData
    
    if (userQuery.data.length === 0) {
      // 新用户，创建记录
      const now = new Date()
      const newUser = {
        _openid: openId,
        nickName: event.nickName || '数独玩家',
        avatarUrl: event.avatarUrl || '',
        gender: event.gender || 0,
        createTime: now,
        updateTime: now,
        lastLoginTime: now,
        totalGames: 0,
        totalWins: 0,
        totalPlayTime: 0,
        level: 1,
        experience: 0
      }
      
      const addResult = await db.collection('users').add({
        data: newUser
      })
      
      userData = {
        ...newUser,
        _id: addResult._id,
        isNewUser: true
      }
      
      console.log('新用户注册成功:', openId)
    } else {
      // 老用户，更新最后登录时间
      userData = userQuery.data[0]
      
      await db.collection('users').doc(userData._id).update({
        data: {
          lastLoginTime: new Date(),
          // 如果传入了新的用户信息，更新
          ...(event.nickName && { nickName: event.nickName }),
          ...(event.avatarUrl && { avatarUrl: event.avatarUrl }),
          ...(event.gender !== undefined && { gender: event.gender })
        }
      })
      
      userData.isNewUser = false
      console.log('用户登录成功:', openId)
    }
    
    return {
      success: true,
      data: {
        openId: openId,
        userId: userData._id,
        nickName: userData.nickName,
        avatarUrl: userData.avatarUrl,
        gender: userData.gender,
        level: userData.level,
        experience: userData.experience,
        totalGames: userData.totalGames,
        totalWins: userData.totalWins,
        isNewUser: userData.isNewUser
      }
    }
  } catch (err) {
    console.error('登录失败:', err)
    return {
      success: false,
      error: err.message
    }
  }
}
